const _url = "https://jjyl.yl.jxxd.cn/api/mini/v1/";

import { getAppEnum } from "@/utils/appDataEnum"
// const _url = "http://localhost:3000"

const BASE_URL = _url;//https://m1.apifoxmock.com

const getAppToken = async () => {
	return new Promise((resolve, reject) => {
		const app = getApp();
		const token = app[getAppEnum.LoginToken]
		if (token) {
			return resolve(token)
		} else {
			uni.login({
				provider: 'weixin', //使用微信登录
				success: function (loginRes) {
					return resolve(loginRes.code)
				}, fail: function (error) {
					return reject('weixin login error')
				}
			});
		}

	})
}

// 拦截器
const requestInterceptor = async (config) => {
	config.header = {
		apifoxToken: "RXUopu3UCH6gKBXjhGo0s"
	}
	const result = await getAppToken();
	console.log("result:", result)
	config.header.Authorization = 'Bearer ' + result;
	return config;
};

const responseInterceptor = (response) => {
	// 你可以在这里统一处理成功响应
	console.log('response:', response)
	const app = getApp();
	if (response.header?.token) {
		app[getAppEnum.LoginToken] = response.header?.token;
	}
	return response;
};

const errorInterceptor = (error) => {
	// 统一处理错误
	uni.showToast({
		title: error.errMsg || '请求失败',
		icon: 'none',
		duration: 2000
	});
	return Promise.reject(error);
}

// 核心请求函数（类 axios 封装）
const request = async (config) => {
	// 请求拦截
	config = await requestInterceptor(config);

	return new Promise((resolve, reject) => {
		// 显示 loading（可全局配置或按需关闭）
		if (config.loading !== false) {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
		}
		console.log('request:', config, BASE_URL)
		uni.request({
			url: BASE_URL + config.url,
			method: config.method || 'GET',
			data: config.data || {},
			header: config.header || {
				'Content-Type': 'application/json'
			},
			timeout: config.timeout || 10000,

			success: (res) => {
				if (config.loading !== false) {
					uni.hideLoading();
				}

				// 响应拦截
				const interceptedRes = responseInterceptor(res);
				console.log('interceptedRes:', interceptedRes)
				// 通常后端会返回 { code, msg, data } 结构
				if (interceptedRes.statusCode === 200) {
					resolve(interceptedRes.data); // 直接返回 data
				} else {
					errorInterceptor(new Error(`HTTP ${res.statusCode}`));
					reject(interceptedRes);
				}
			},

			fail: (err) => {
				if (config.loading !== false) {
					uni.hideLoading();
				}
				errorInterceptor(err);
				reject(err);
			}
		});
	});
}

// 挂载方法：get, post, put, delete
request.get = (url, config = {}) => {
	return request({
		...config,
		url,
		method: 'GET'
	});
};

request.post = (url, data, config = {}) => {
	return request({
		...config,
		url,
		method: 'POST',
		data
	});
};

request.put = (url, data, config = {}) => {
	return request({
		...config,
		url,
		method: 'PUT',
		data
	});
};


request.delete = (url, data, config = {}) => {
	return request({
		...config,
		url,
		method: 'DELETE',
		data
	});
};

// 导出实例
export default request;